package com.example.timeemail.home;

import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import androidx.appcompat.app.AlertDialog;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.timeemail.MainActivity;
import com.example.timeemail.R;
import com.example.timeemail.entity.Letter;
import com.example.timeemail.home.view.PullUpListView;
import com.example.timeemail.letter.EmailActivity;
import com.example.timeemail.utils.LetterResult;
import com.example.timeemail.utils.LoginRequest;
import com.example.timeemail.utils.LoginResult;
import com.example.timeemail.utils.OkHttpUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.example.timeemail.city.Images.imageUrls;


/**
 * User:Shine
 * Date:2015-10-20
 * Description:
 */
public class HomeFragment extends Fragment {

    private SwipeRefreshLayout refreshLayout;
    private PullUpListView listView;
    private ArrayList<ItemEntity> lists;
    private ListAdapter adapter;
    private Integer page;
    private Integer count;
    List<Letter> data;
    AlertDialog alert ;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_home, container, false);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        refreshLayout = getActivity().findViewById(R.id.swipeRe_fresh);
        listView = getActivity().findViewById(R.id.list_view);
        lists = new ArrayList<>();
        data = new ArrayList<>();

        LoginRequest request = new LoginRequest();
        page = 1;
        count = 0;
        request.setPage(page);
        showLetterWithOkHttp(request);
        refreshLayout.setOnRefreshListener(() -> refreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoginRequest request = new LoginRequest();
                page++;
                request.setPage(page);
                showLetterWithOkHttp(request);
                //Toast.makeText(getActivity(), "sdfsdfsdf", Toast.LENGTH_SHORT).show();
            }
        }, 3000));


        listView.setPullUpListViewCallBack(() -> listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                ItemEntity itemEntity = new ItemEntity();
                itemEntity.setTitle("模拟数据");
                itemEntity.setContent("这里是时光邮箱的模拟数据，十分欢迎您使用时光邮箱app，希望您可以完成自己的心愿");
                itemEntity.setUrl("https://img.ivsky.com/img/tupian/co/202009/13/yellowstone_national_park-005.jpg");
                lists.add(itemEntity);
                adapter.mData = lists;
                adapter.notifyDataSetChanged();
                listView.completeRefresh();
                //Toast.makeText(getActivity(), "sdfdsfsdfds", Toast.LENGTH_SHORT).show();
            }
        }, 2000));

        //点击展示事件
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            ItemEntity item = adapter.getItem(i);
            /*//tos(data.get(i).getCoursename(),data.get(i).getClassroom());
//            private void tos(String name,String tel){
//                AlertDialog alert = new AlertDialog.Builder(this).create();
//                alert.setTitle(name);
//                alert.setIcon(R.drawable.ic_launcher_foreground);
//                alert.setMessage(tel);
//                alert.show();
//            }
            if(i >= 5 && i < 10) {
                Toast.makeText(getActivity(), "发送时间：\n" + data.get(i - 5).getCoursetime() + "\n\n状态：\n" + data.get(i - 5).getCoursetype() + "\n\n标题：\n" + data.get(i - 5).getCoursename() + "\n\n内容：\n" + data.get(i - 5).getClassroom(), Toast.LENGTH_LONG).show();
            } else if(i == 4){
                String ss = "发送时间：\n"+data.get(2).getCoursetime()+"\n\n状态：\n" + data.get(4).getCoursetype() + "\n\n标题：\n" + data.get(3).getCoursename() + "\n\n内容：\n" + "不管你学什么专业，找工作一定要找个你喜欢的，这样你每天早晨6：00到晚上8：00都是高兴的。再找个喜欢的人在一起，这样你晚上8：00到早晨6：00也是开心的，这就是生活。";
                Toast.makeText(getActivity(), ss, Toast.LENGTH_LONG).show();
            } else if(i == 0){
                String ss = "发送时间：\n"+data.get(2).getCoursetime()+"\n\n状态：\n" + data.get(4).getCoursetype() + "\n\n标题：\n" + data.get(3).getCoursename() + "\n\n内容：\n" + "想要放弃的时候，想想当时为什么会选择？只是因为难，只是因为学不好，就随便地放弃吗？\n" +
                        "\n" +
                        "是你没有当回事，是你抱着玩一玩的心态，所以才会心不在焉，不愿意练习不愿意看镜子中笨拙的自己。\n" +
                        "不要放弃。不管是不是热爱。\n" +
                        "\n" +
                        "记得要练习。";
                Toast.makeText(getActivity(), ss, Toast.LENGTH_LONG).show();
            }else if(i == 1){
                String ss = "发送时间：\n"+data.get(2).getCoursetime()+"\n\n状态：\n" + data.get(4).getCoursetype() + "\n\n标题：\n" + data.get(3).getCoursename() + "\n\n内容：\n" + "One day,you will be just a memory for some people.So do your best and be a good one. \n" +
                        "总有一天，你会成为别人的一段回忆，所以你要努力使之变得美好！";
                Toast.makeText(getActivity(), ss, Toast.LENGTH_LONG).show();
            }else if(i == 2){
                String ss = "发送时间：\n"+data.get(2).getCoursetime()+"\n\n状态：\n" + data.get(4).getCoursetype() + "\n\n标题：\n" + data.get(3).getCoursename() + "\n\n内容：\n" + "You're about to burst into tears at some moment and you don't even know why.";
                Toast.makeText(getActivity(), ss, Toast.LENGTH_LONG).show();
            }else if(i == 3){
                String ss = "发送时间：\n"+data.get(2).getCoursetime()+"\n\n状态：\n" + data.get(4).getCoursetype() + "\n\n标题：\n" + data.get(3).getCoursename() + "\n\n内容：\n" + "世界上最远的距离，不是爱，不是恨，而是熟悉的人，渐渐变得陌生。";
                Toast.makeText(getActivity(), ss, Toast.LENGTH_LONG).show();
            }else {
                String ss = "发送时间：\n"+data.get(2).getCoursetime()+"\n\n状态：\n" + data.get(4).getCoursetype() + "\n\n标题：\n" + "模拟数据" + "\n\n内容：\n" + "这里是模拟数据，诚挚的欢迎您使用时光邮箱，希望您可以在这里有良好的用户体验";
                Toast.makeText(getActivity(), ss, Toast.LENGTH_LONG).show();
            }*/
//            System.out.println("萨达萨达就包括第八届：" + i + "\n萨达萨达就包括第八届：" + l);

            alert(item.getTitle(), item.getContent());
        });
    }


    //获取公开信件内容
    private void showLetterWithOkHttp(LoginRequest request) {
        OkHttpUtil.showLetterWithOkHttp(request, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("HomeFragment", "获取公开信件内容请求失败");
                Toast.makeText(getActivity(), "获取信件内容请求失败" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }

            //请求成功，获取服务器返回数据
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取返回内容
                final String responseData = response.body().string();
                //在主线程更新ui和响应用户操作
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            LetterResult result = new Gson().fromJson(responseData, LetterResult.class);
                            if (result.getStatus().equals("200")) {
                                List<Letter> data1 = result.getData();
                                for (Letter letter:data1) {
                                    ItemEntity itemEntity = new ItemEntity();
                                    itemEntity.setTitle(letter.getCoursename());
                                    itemEntity.setContent(letter.getClassroom());
                                    itemEntity.setUrl(imageUrls[count++ % 30]);
                                    lists.add(itemEntity);
                                    data.add(letter);
                                }

                                if (page == 1) {
                                    adapter = new ListAdapter(getActivity(), lists);

                                    listView.setAdapter(adapter);
                                    listView.initBottomView();
                                }else {
                                    adapter.mData = lists;
                                    adapter.notifyDataSetChanged();
                                    refreshLayout.setRefreshing(false);
                                }
                            } else {
                                Toast.makeText(getActivity(), result.getMsg(), Toast.LENGTH_SHORT).show();
                                adapter.mData = lists;
                                adapter.notifyDataSetChanged();
                                refreshLayout.setRefreshing(false);
                            }
                        }catch (Exception e) {
                            Toast.makeText(getActivity(), "数据解析失败，请刷新重试!!", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    private void alert(String name,String content){
        alert = new AlertDialog.Builder(getActivity()).create();
        alert.setTitle(name);
        alert.setIcon(R.drawable.ic_launcher_foreground);
        alert.setMessage(content);
        alert.show();
    }
}


